package com.youi.webapp;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.youi.util.LogUtil;
import com.youi.util.ObjectUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.youi.common.Common;
import com.youi.common.DelStatus;
import com.youi.common.SessionKey;
import com.youi.entity.Goods;
import com.youi.entity.Goodssize;
import com.youi.entity.Groupleader;
import com.youi.entity.Leaderfan;
import com.youi.entity.Leaderprofit;
import com.youi.entity.Leaderstore;
import com.youi.entity.Merchant;
import com.youi.entity.Ordergoods;
import com.youi.entity.Orderprofitdetail;
import com.youi.entity.Refundorder;
import com.youi.entity.User;
import com.youi.entity.Userorder;
import com.youi.entity.Userwechat;
import com.youi.entity.Yibaodivide;
import com.youi.entity.Yibaopayment;
import com.youi.entity.Yibaorefund;
import com.youi.exception.BusinessException;
import com.youi.manage.HttpRequestManage;
import com.youi.manage.HttpSessionManage;
import com.youi.model.GoodsStatistics;
import com.youi.service.GoodsService;
import com.youi.service.GoodssizeService;
import com.youi.service.GroupleaderService;
import com.youi.service.LeaderfanService;
import com.youi.service.LeaderprofitService;
import com.youi.service.LeaderstoreService;
import com.youi.service.MerchantService;
import com.youi.service.OrdergoodsService;
import com.youi.service.OrderprofitdetailService;
import com.youi.service.RefundorderService;
import com.youi.service.SetleaderlevelService;
import com.youi.service.UserService;
import com.youi.service.UserorderService;
import com.youi.service.UserwechatService;
import com.youi.service.YibaodivideService;
import com.youi.service.YibaopaymentService;
import com.youi.service.YibaorefundService;
import com.youi.third.yibaopay.YibaopayUtil;
import com.youi.third.yibaopay.model.Divideresult;
import com.youi.third.yibaopay.model.Refundresult;
import com.youi.util.CommonInfoUtil;
import com.youi.util.DateUtil;
import com.youi.util.JsonUtil;

@Controller
public class ScriptController  extends HttpRequestManage{
	
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private OrdergoodsService ordergoodsService;
	@Autowired
	private UserorderService userorderService;
	@Autowired
	private GoodssizeService goodssizeService;
	@Autowired
	private OrderprofitdetailService orderprofitdetailService;
	@Autowired
	private UserwechatService userwechatService;
	@Autowired
	private SetleaderlevelService setleaderlevelService;
	@Autowired
	private LeaderfanService leaderfanService;
	@Autowired
	private GroupleaderService groupleaderService;
	@Autowired
	private LeaderstoreService leaderstoreService;
	@Autowired
	private UserService userService;
	@Autowired
	private MerchantService merchantService;
	@Autowired
	private LeaderprofitService leaderprofitService;
	@Autowired
	private YibaopaymentService yibaopaymentService;
	@Autowired
	private YibaorefundService yibaorefundService;
	@Autowired
	private RefundorderService refundorderService;
	@Autowired
	private YibaodivideService yibaodivideService;
	
	/**
	 * 将3号之前的商品重新计算“销量”（根据商品的对应订单的商品数量计算）
	 * @param modelMap
	 * @param request
	 * @return
	 * @throws BusinessException
	 * @throws IOException
	 * @throws ParseException
	 */
	@ResponseBody
	@RequestMapping("computeSaleGoodsNumByBeforethird")
	public  String  getSaleGoodsNum(ModelMap modelMap,HttpServletRequest request) throws BusinessException, IOException, ParseException {
		List<GoodsStatistics> list=new ArrayList<GoodsStatistics>();
		Map<String, Object> prams=new HashMap<String, Object>();
		prams.put(Common.DELSTATUS, DelStatus.NODEL);
		Map<String, Object> endTime=new HashMap<String, Object>();
		endTime.put(Common.GMTCREATED,DateUtil.simpdfyMdHms.parse("2020-01-03 23:59:59"));
		List<Goods>goodsList=goodsService.getByParamsAll(prams, null, null, null, null);
		for (Goods goods : goodsList) {
			Integer count=0;
			prams=new HashMap<String, Object>();
			prams.put(Common.DELSTATUS, DelStatus.NODEL);
			prams.put("goodsId", goods.getId());
			List<Ordergoods>ordergoodsList=ordergoodsService.getByParams(prams);
			for (Ordergoods ordergoods : ordergoodsList) {
				prams=new HashMap<String, Object>();
				prams.put(Common.DELSTATUS, DelStatus.NODEL);
				prams.put(Common.ID, ordergoods.getOrderId());
				prams.put(Common.STATUS, Arrays.asList(0,1,2,3,4,5));
				Userorder userorder=userorderService.getByParam(prams);
				if (userorder!=null) {
					count+=ordergoods.getCount();					
				}
				prams=new HashMap<String, Object>();
				prams.put(Common.DELSTATUS, DelStatus.NODEL);
				prams.put("goodsId", goods.getId());
				List<Goodssize> goodssizeList=goodssizeService.getByParams(prams);
				if (goodssizeList!=null&&goodssizeList.size()>0) {
					Integer stockNum=0;
					Goodssize goodssize=goodssizeList.get(0);
					goodssize.setSaleNum(count);
					goodssize.setStockNum(goods.getRealStockCnt());
					goodssize.setRealStockNum(goodssize.getStockNum()-goodssize.getSaleNum());
					goodssizeService.saveOrUpdate(goodssize);	
					for (Goodssize goodssize2 : goodssizeList) {
						stockNum+=goodssize2.getStockNum();
					}
					goods.setRealSaleCnt(count);
					goods.setRealStockCnt(stockNum);
					goodsService.saveOrUpdate(goods);
				}
			}	
			
		}	
		return JsonUtil.toJson(CommonInfoUtil.SUCCESS,"操作成功");		
	}

	
	/**
	 * 
	 * 将3号到目前为止销量为“0”的商品，将实时库存设置为“录入库存”
	 * @param modelMap
	 * @param request
	 * @return
	 * @throws BusinessException
	 * @throws IOException
	 * @throws ParseException
	 */
	@ResponseBody
	@RequestMapping("getSaleGoodssizeNum")
	public  String  getSaleGoodssizeNum(ModelMap modelMap,HttpServletRequest request) throws BusinessException, IOException, ParseException {		
		Map<String, Object> prams=new HashMap<String, Object>();
		prams.put(Common.DELSTATUS, DelStatus.NODEL);
		prams.put("realSaleCnt", 0);
		Map<String, Object> startTime=new HashMap<String, Object>();
		startTime.put(Common.GMTCREATED,DateUtil.simpdfyMdHms.parse("2020-01-03 00:00:00"));
		Map<String, Object> endTime=new HashMap<String, Object>();
		endTime.put(Common.GMTCREATED,DateUtil.simpdfyMdHms.parse("2020-01-12 23:59:59"));
		List<Goods>goodsList=goodsService.getByParamsAll(prams, null, null, startTime, endTime);
		if (goodsList!=null&&goodsList.size()>0) {
			for (Goods goods : goodsList) {
				Integer count=0;
				prams=new HashMap<String, Object>();
				prams.put(Common.DELSTATUS, DelStatus.NODEL);
				prams.put("goodsId", goods.getId());
				List<Goodssize> goodssizeList=goodssizeService.getByParams(prams);
				if (goodssizeList!=null&&goodssizeList.size()>0) {
					for (Goodssize goodssize : goodssizeList) {
						goodssize.setRealStockNum(goodssize.getStockNum());	
						count+=goodssize.getRealStockNum();
					}
					goodssizeService.saveOrUpdateAll(goodssizeList);
				}
				goods.setRealStockCnt(count);
			}
			goodsService.saveOrUpdateAll(goodsList);
		}		
		return JsonUtil.toJson(CommonInfoUtil.SUCCESS,"操作成功");	
	}
	
	/**
	 * 将3号到目前为止“有销量”的商品，将所有规格的“录入库存”设置为“300”
	 * @param modelMap
	 * @param request
	 * @return
	 * @throws BusinessException
	 * @throws IOException
	 * @throws ParseException
	 */
	@ResponseBody
	@RequestMapping("getOtherSaleGoodssizeNum")
	public  String  getOtherSaleGoodssizeNum(ModelMap modelMap,HttpServletRequest request) throws BusinessException, IOException, ParseException {		
		Map<String, Object> prams=new HashMap<String, Object>();
		prams.put(Common.DELSTATUS, DelStatus.NODEL);
		Map<String, Object> startTime=new HashMap<String, Object>();
		startTime.put("realSaleCnt", 0);
		startTime.put(Common.GMTCREATED,DateUtil.simpdfyMdHms.parse("2020-01-03 00:00:00"));
		Map<String, Object> endTime=new HashMap<String, Object>();
		endTime.put(Common.GMTCREATED,DateUtil.simpdfyMdHms.parse("2020-01-12 23:59:59"));
		List<Goods>goodsList=goodsService.getByParamsAll(prams, null, null, startTime, endTime);
		if (goodsList!=null&&goodsList.size()>0) {
			for (Goods goods : goodsList) {
				Integer count=0;
				prams=new HashMap<String, Object>();
				prams.put(Common.DELSTATUS, DelStatus.NODEL);
				prams.put("goodsId", goods.getId());
				List<Goodssize> goodssizeList=goodssizeService.getByParams(prams);
				if (goodssizeList!=null&&goodssizeList.size()>0) {
					for (Goodssize goodssize : goodssizeList) {
						goodssize.setStockNum(300);
						goodssizeService.saveOrUpdate(goodssize);
						count+=goodssize.getStockNum();
					}										
				}
				goods.setRealStockCnt(count);
			}
			goodsService.saveOrUpdateAll(goodsList);
		}		
		return JsonUtil.toJson(CommonInfoUtil.SUCCESS,"操作成功");	
	}
	
	/**
	 * 将3号到目前为止“有销量”的商品，将商品的总销量设置为第一个规格的销量
	 * @param modelMap
	 * @param request
	 * @return
	 * @throws BusinessException
	 * @throws IOException
	 * @throws ParseException
	 */
	@ResponseBody
	@RequestMapping("onemoreSaleGoodssizeNum")
	public  String  onemoreSaleGoodssizeNum(ModelMap modelMap,HttpServletRequest request) throws BusinessException, IOException, ParseException {		
		Map<String, Object> prams=new HashMap<String, Object>();
		prams.put(Common.DELSTATUS, DelStatus.NODEL);
		Map<String, Object> startTime=new HashMap<String, Object>();
		startTime.put("realSaleCnt", 0);
		startTime.put(Common.GMTCREATED,DateUtil.simpdfyMdHms.parse("2020-01-03 00:00:00"));
		Map<String, Object> endTime=new HashMap<String, Object>();
		endTime.put(Common.GMTCREATED,DateUtil.simpdfyMdHms.parse("2020-01-12 23:59:59"));
		List<Goods>goodsList=goodsService.getByParamsAll(prams, null, null, startTime, endTime);
		for (Goods goods : goodsList) {
			Integer count=0;
			prams=new HashMap<String, Object>();
			prams.put(Common.DELSTATUS, DelStatus.NODEL);
			prams.put("goodsId", goods.getId());
			List<Ordergoods>ordergoodsList=ordergoodsService.getByParams(prams);
			for (Ordergoods ordergoods : ordergoodsList) {
				prams=new HashMap<String, Object>();
				prams.put(Common.DELSTATUS, DelStatus.NODEL);
				prams.put(Common.ID, ordergoods.getOrderId());
				prams.put(Common.STATUS, Arrays.asList(0,1,2,3,4,5));
				Userorder userorder=userorderService.getByParam(prams);
				if (userorder!=null) {
					count+=ordergoods.getCount();					
				}
				prams=new HashMap<String, Object>();
				prams.put(Common.DELSTATUS, DelStatus.NODEL);
				prams.put("goodsId", goods.getId());
				List<Goodssize> goodssizeList=goodssizeService.getByParams(prams);
				if (goodssizeList!=null&&goodssizeList.size()>0) {
					Goodssize goodssize=goodssizeList.get(0);
					goodssize.setSaleNum(count);		
					goodssizeService.saveOrUpdate(goodssize);
					goods.setRealSaleCnt(count);
					goodsService.saveOrUpdate(goods);
				}		
			}
													
		}
		return JsonUtil.toJson(CommonInfoUtil.SUCCESS,"操作成功");	
	}

	////////////////////////////////////////////////////////////////////////////////
	// 以下是重新设置佣金数据

	//万分之三，也就是0.03%
	static private double SERVICE_RATE = 0.003;

	//帮助方法，用一个键值对获取参数
	static private Map<String,Object> mapWithOneEntry(String key,Object value){
		HashMap<String,Object> params=new HashMap<>();
		params.put(key,value);
		return params;
	}
	//帮助方法，用键值队获取参数，增加delstatus == 0条件
	static private Map<String,Object> mapWithOneEntryNoDel(String key,Object value){
		Map<String,Object> params = mapWithOneEntry(key,value);
		params.put(Common.DELSTATUS,DelStatus.NODEL);
		return params;
	}

	//帮助方法，四舍六入五留双
	//以后应该从entity开始直接支持BigDecimal
	static private double ROUND_HALF_EVEN(double value){
		BigDecimal result = new BigDecimal(value).setScale(2, BigDecimal.ROUND_HALF_EVEN);
		return result.doubleValue();
	}

	/**
	 * 重置佣金数据
	 * @param modelMap
	 * @param request
	 * @return
	 * @throws BusinessException
	 * @throws IOException
	 * @throws ParseException
	 */
	@ResponseBody
	@RequestMapping("resetorderprofitdata")
	public  String  resetorderprofitdata(ModelMap modelMap,HttpServletRequest request) throws BusinessException, IOException, ParseException {
//		String orderNo=getString("orderNo", request);
		Map<String, Object> prams=new HashMap<String, Object>();
		prams.put(Common.DELSTATUS, DelStatus.NODEL);
		prams.put(Common.STATUS, Arrays.asList(1,2,3,4,5));
//		prams.put("orderNo", orderNo);
		//获取所有订单（取消注释则是按orderNo获取）
		List<Userorder> userorderList=userorderService.getByParams(prams);
		if (userorderList==null&&userorderList.size()>0) {
			return JsonUtil.toJson(CommonInfoUtil.NULLDATA,"空数据");
		}
		for (Userorder userorder : userorderList) {

//			//为了调错，这四条记录是出错记录
//			Long uoid = userorder.getId();
//			if ((uoid!=78)&&(uoid!=1726)&&(uoid!=2416)&&(uoid!=2547)) {
//				continue;
//			}

			prams=new HashMap<String, Object>();
			prams.put(Common.DELSTATUS, DelStatus.NODEL);
			prams.put("orderNo", userorder.getOrderNo());
			//对每张订单获取分利记录
			Orderprofitdetail orderprofitdetail=orderprofitdetailService.getByParam(prams);
			//如果没有分利记录则新建一个
			if (orderprofitdetail==null) {
				orderprofitdetail=new Orderprofitdetail(null, userorder.getOrderNo(), userorder.getPayableAmount());
				orderprofitdetail.setGmtCreated(new Date());
				orderprofitdetail.setDelStatus(DelStatus.NODEL);
			}else{
				//如果接下来整个数据全部要重新覆盖，那么先把所有的值设置成null
				orderprofitdetail.setType(null);
				orderprofitdetail.setCommission(null);
				orderprofitdetail.setLeaderId1(null);
				orderprofitdetail.setFirstUser(null);
				orderprofitdetail.setFirstAmount(null);
				orderprofitdetail.setLeaderId2(null);
				orderprofitdetail.setSecondUser(null);
				orderprofitdetail.setSecondAmount(null);
				orderprofitdetail.setPlatAmount(null);
				orderprofitdetail.setMerchantId(null);
				orderprofitdetail.setMerAmount(null);
				orderprofitdetail.setServiceCharge(null);
			}
			//获取当前订单的用户对象
			User user=userService.get(userorder.getUserId()); //原来写为 .getId()
			if (user==null){
				LogUtil.Info("fail fetch user:"+userorder.getUserId());
				continue;
			}

			//用当前订单的店铺ID获取店铺
			Merchant merchant=merchantService.get(userorder.getMerchantId());
			if (merchant==null){
				LogUtil.Info("fail fetch merchant:"+userorder.getMerchantId());
				continue;
			}

			//计算分利逻辑
			getLeaderprofit(userorder, userorder.getPayableAmount(), user, merchant, orderprofitdetail);
		}
		return JsonUtil.toJson(CommonInfoUtil.SUCCESS,"操作成功");
	}
	
	/**
	 * 重置佣金
	 * @param modelMap
	 * @param request
	 * @return
	 * @throws BusinessException
	 */
	@ResponseBody
	@RequestMapping("setleaderprofit")
	public  String  setleaderprofit(ModelMap modelMap,HttpServletRequest request) throws BusinessException{
		Map<String, Object> prams=new HashMap<String, Object>();
		prams.put(Common.DELSTATUS, DelStatus.NODEL);		
		Map<String, Object> endTime=new HashMap<String, Object>();
		endTime.put("frozen",0);
		List<Leaderprofit> leaderprofitList=leaderprofitService.getByParamsAll(prams, null, null, endTime, null);
		for (Leaderprofit leaderprofit : leaderprofitList) {
			leaderprofit.setBalance(0.00);
			leaderprofit.setFrozen(leaderprofit.getTotalAmount());
			leaderprofitService.saveOrUpdate(leaderprofit);
		}		
		return JsonUtil.toJson(CommonInfoUtil.SUCCESS,"操作成功");
	}
	
	/**
	 * 把可提现佣金放入可提现处
	 * @param modelMap
	 * @param request
	 * @return
	 * @throws BusinessException
	 */
	@ResponseBody
	@RequestMapping("setCommsToBlance")
	public  String  setleaderprofitByReset(ModelMap modelMap,HttpServletRequest request) throws BusinessException{		
		Map<String, Object> params=new HashMap<String, Object>();
		params.put(Common.DELSTATUS, DelStatus.NODEL);
		params.put("merchantStatus", 1);
		params.put("platformStatus", 1);
		params.put("refund", -1);
		List<Userorder> userorderList=userorderService.getByParams(params);
		for (Userorder userorder : userorderList) {
			params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);
			params.put("orderNo", userorder.getOrderNo());
			Orderprofitdetail orderprofitdetail=orderprofitdetailService.getByParam(params);
			if (orderprofitdetail!=null) {
				//判断是否有一级佳选官的id
				if (orderprofitdetail.getLeaderId1()!=null) {
					params=new HashMap<String, Object>();
					params.put(Common.DELSTATUS, DelStatus.NODEL);
					params.put("leaderId", orderprofitdetail.getLeaderId1());
					Leaderprofit firstLeaderprofit=leaderprofitService.getByParam(params);
					if (firstLeaderprofit!=null) {
						if (firstLeaderprofit.getFrozen()-orderprofitdetail.getFirstAmount()>0) {
							firstLeaderprofit.setFrozen(firstLeaderprofit.getFrozen()-orderprofitdetail.getFirstAmount());
							firstLeaderprofit.setBalance(firstLeaderprofit.getBalance()+orderprofitdetail.getFirstAmount());	
							leaderprofitService.saveOrUpdate(firstLeaderprofit);
						}
					}
				}
				//判断是否有二级佳选官的id
				if (orderprofitdetail.getLeaderId2()!=null) {
					params=new HashMap<String, Object>();
					params.put(Common.DELSTATUS, DelStatus.NODEL);
					params.put("leaderId", orderprofitdetail.getLeaderId2());
					Leaderprofit secondLeaderprofit=leaderprofitService.getByParam(params);
					if (secondLeaderprofit!=null) {
						if (secondLeaderprofit.getFrozen()-orderprofitdetail.getSecondAmount()>0) {
							secondLeaderprofit.setFrozen(secondLeaderprofit.getFrozen()-orderprofitdetail.getSecondAmount());
							secondLeaderprofit.setBalance(secondLeaderprofit.getBalance()+orderprofitdetail.getSecondAmount());
							leaderprofitService.saveOrUpdate(secondLeaderprofit);
						}							
					}
				}					
			}
		}		
		return JsonUtil.toJson(CommonInfoUtil.SUCCESS,"操作成功");
	}
	
	
	
	/**
	 * 团长佣金信息分账
	 */
	public void getLeaderprofit(Userorder userorder,Double payAmount,User user,Merchant merchant,Orderprofitdetail orderprofitdetail) {
		LogUtil.Info("getLeaderprofit:"+userorder.getId());
//		DecimalFormat amount=new DecimalFormat("0.00");
		//商家佣金，猜测这里是85%
		Double merchantComms=ROUND_HALF_EVEN(payAmount*(1-(merchant.getCommissionRatio()*0.01)));
		//手续费，0.3%应该是 0.003，原为0.003
		Double serviceCharge=ROUND_HALF_EVEN(payAmount*SERVICE_RATE);
		Double platComms=null;
		//判断用户身份，0非粉丝 1粉丝 2团长
		UserIdentity identity=checkUserIdentity(userorder); //获取订单创建时点用户的身份
		LogUtil.Info("identity:"+identity.type);
		if ((identity.type==0)&&(userorder.getLeaderId()==null)) {
			//当用户为非粉丝和非团长时，而且不通过链接购买
			platComms=payAmount-merchantComms-serviceCharge;//平台佣金 认为payAmount是小数点后两位标准，所以不做四舍六入
			orderprofitdetail.setType(2); //订单类型(0顶级团长分佣 1二级团长分佣 2平台分佣) ,原来为0，这里改成2
			orderprofitdetail.setPlatAmount(platComms);
			orderprofitdetail.setMerchantId(userorder.getMerchantId());
			orderprofitdetail.setMerAmount(merchantComms);
			orderprofitdetail.setServiceCharge(serviceCharge);
			orderprofitdetail.setGmtModify(new Date());
			orderprofitdetailService.saveOrUpdate(orderprofitdetail);
			LogUtil.Info("type == 0 save");
		}else if ((identity.type==1)||((identity.type==0)&&(userorder.getLeaderId()!=null))) {
			//当用户为粉丝的时候，或者通过链接购买的时候
			getleaderComms(identity, orderprofitdetail, userorder, payAmount, merchantComms, serviceCharge);
		}else if (identity.type==2) {
			//当用户为团长的时候
//			getLeaderOneselfComms(amount, identity, orderprofitdetail, userorder, payAmount, merchantComms, serviceCharge, platComms,1);
			getleaderComms(identity, orderprofitdetail, userorder, payAmount, merchantComms, serviceCharge);
		}else{
			LogUtil.Info("fail identity.type:"+identity.type);
		}
	}

	//获取用户身份过程中取到的数据结构
	private static class UserIdentity{
		final int type; //0非粉丝 1粉丝 2团长
		final Groupleader groupleader;
		final Leaderfan leaderfan;
		private UserIdentity(int type, Groupleader groupleader, Leaderfan leaderfan) {
			this.type = type;
			this.groupleader = groupleader;
			this.leaderfan = leaderfan;
		}
	}
	/**
	 * 检测订单用户身份
	 * @param userorder
	 * @return
	 */
	private UserIdentity checkUserIdentity(Userorder userorder) {
		Date beforeDate = userorder.getGmtCreated();
		Long userId = userorder.getUserId();
		//首先从groupleader获取
		//只要这个人之前出现在groupLeader表，那他当时就是团长
		Groupleader groupleader = groupleaderService.getByParamss(
				mapWithOneEntry(Common.USERID ,userId),
				null,null,null,
				mapWithOneEntry(Common.GMTCREATED ,beforeDate)
		);
		if (groupleader != null ){
			return new UserIdentity(2,groupleader,null);
		}
		//从userorder里的unioid判断他是否是粉丝
		Leaderfan leaderfan = leaderfanService.getByParamss(
				mapWithOneEntry("unionid",userorder.getUnioid()),
				null,null,null,
				mapWithOneEntry(Common.GMTCREATED,beforeDate)
		);
		if (leaderfan == null){ //可能不必要？
			Userwechat userwechat = userwechatService.getByParam(mapWithOneEntryNoDel(Common.USERID,userId));
			if (userwechat!=null){
				leaderfan = leaderfanService.getByParamss(
						mapWithOneEntry("unionid",userwechat.getUnionid()),
						null,null,null,
						mapWithOneEntry(Common.GMTCREATED,beforeDate)
				);
			}
		}
		if (leaderfan != null ){
			return new UserIdentity(1,null,leaderfan);
		}
		return new UserIdentity(0,null,null);
	}

	
	/**
	 * 团长佣金计算方法
	 * @param userIdentity
	 * @param orderprofitdetail
	 * @param userorder
	 * @param payAmount
	 * @param merchantComms
	 * @param serviceCharge
	 */
	private void getleaderComms(UserIdentity userIdentity,Orderprofitdetail orderprofitdetail,Userorder userorder,double payAmount,double merchantComms,double serviceCharge) {
		Groupleader groupleader;
		//自己不是团长
		if (userIdentity.groupleader == null) {
			LogUtil.Info("goupleader == null");
			//如果已经是粉丝，不为空
			Leaderfan leaderfan = userIdentity.leaderfan;
			Long leaderId;
			//如果通过链接进入，能取到userorder.leaderId
			if (leaderfan == null) {
				leaderId = userorder.getLeaderId();
				LogUtil.Info("get userorder.leaderId");
			} else {
				leaderId = leaderfan.getLeaderId();
				LogUtil.Info("get leaderfan.leaderId");
			}
			if (leaderId == null) {
				LogUtil.Info("fail get leaderId (getleaderComms)");
			}
			//用leaderId获取groupleader（实际上只用来获取名字，和验证存在）
			//不做noDel判断，因为leader和groupLeader是一对一的
			groupleader = groupleaderService.getByParam(mapWithOneEntry(Common.ID, leaderId));
			if (groupleader == null){
				LogUtil.Info("fail fetch groupleader(leaderId):" + leaderId);
				return;
			}
		}else{ //自己就是团长
			LogUtil.Info("get groupleader by userId");
			//从下单人直接获取groupLeader
			//只有 orderid = 3038,3040，leaderstore的leaderId=26525,26526 的数据会出现多条，但多条的level都是一样的
			groupleader=groupleaderService.getByParam(mapWithOneEntry(Common.USERID,userorder.getUserId()));
			if (groupleader == null){
				LogUtil.Info("fail fetch groupleader(userId):" + userorder.getUserId());
				return;
			}
		}

		//用leaderId获取leaderStore信息，店铺注册时间应该小于订单创建时间
		List<Leaderstore> storeList = leaderstoreService.getByParamsList(
				mapWithOneEntry("leaderId", groupleader.getId()),
				null,
				mapWithOneEntry(Common.ID,Common.DESC),
				0,9999,null,
				mapWithOneEntry("gmtReg",userorder.getGmtCreated())
		);
		//取第一个（最新的那个），或者取level=1的那一个（顶级团长）
		Leaderstore leaderstore = null;
		for(Leaderstore lf : storeList) {
			if (lf.getLevel() == 1){
				leaderstore = lf;
				break;
			}else if (leaderstore == null){
				leaderstore = lf;
			}
		}
		if (leaderstore == null){
			LogUtil.Info("fail fetch leaderstore:" + groupleader.getId());
			return;
		}
		if (leaderstore.getLevel()==1) { //团长等级(0普通用户 1顶级团长 2二级团长)
			LogUtil.Info("leaderstore.getLevel()==1");
			//订单为一级团长订单时
			//计算团长佣金
			//1.确定团长佣金比例
			double topLeaderRate=setleaderlevelService.getLeaderRate(1)+setleaderlevelService.getLeaderRate(2);
			//2.计算团长佣金
			double leaderComms= ROUND_HALF_EVEN(payAmount*(topLeaderRate*0.01));
			//3.计算平台佣金
			double platComms=payAmount-merchantComms-leaderComms-serviceCharge; //应该不需要四舍六入
			//添加分佣记录
			orderprofitdetail.setType(0); //(0顶级团长分佣 1二级团长分佣 2平台分佣) 原为type，修改为0

			orderprofitdetail.setLeaderId1(leaderstore.getLeaderId());
			orderprofitdetail.setFirstUser(groupleader.getName());
			orderprofitdetail.setFirstAmount(leaderComms);

			orderprofitdetail.setPlatAmount(platComms);
			orderprofitdetail.setMerchantId(userorder.getMerchantId());
			orderprofitdetail.setMerAmount(merchantComms);
			orderprofitdetail.setServiceCharge(serviceCharge);
			orderprofitdetail.setGmtModify(new Date());
			orderprofitdetailService.saveOrUpdate(orderprofitdetail);
			LogUtil.Info("leaderstore.getLevel()==1 save");
		}else if(leaderstore.getLevel()==2){
			LogUtil.Info("leaderstore.getLevel()==2");
			//当团长为二级团长时
			//1.确定二级团长的佣金
			double secondLeaderComms=ROUND_HALF_EVEN(payAmount*(setleaderlevelService.getLeaderRate(2)*0.01));
			//2.确定一级团长佣金
			double firstLeaderComms=ROUND_HALF_EVEN(payAmount*(setleaderlevelService.getLeaderRate(1)*0.01));
			//3.计算一二级团长佣金的总和
			double allLeaderComms=secondLeaderComms+firstLeaderComms;
			//4.计算平台佣金
			double platComms=payAmount-merchantComms-allLeaderComms-serviceCharge;

			//6.添加一级团长佣金信息
			//用storeId获取店铺的一级团长leaderStore信息
			//取最接近当时时间点的一级团长(部分store有多个一级团长）
			HashMap <String,Object> params=new HashMap<>();
			params.put("storeId", leaderstore.getStoreId());
			params.put("level", 1);
			Leaderstore topLeaderstore=leaderstoreService.getByParamss(
					params,
					null,
					mapWithOneEntry("gmtReg",Common.DESC),
					null,
					mapWithOneEntry("gmtReg",userorder.getGmtCreated())
					);
			if (topLeaderstore == null){
				LogUtil.Info("fail fetch topLeaderstore:" + leaderstore.getStoreId());
				return;
			}

			//获取一级团长的groupLeader信息
			Groupleader firstGroupleader=groupleaderService.getByParam(
					mapWithOneEntry(Common.ID,leaderstore.getLeaderId()));
			if (firstGroupleader==null) {
				LogUtil.Info("fail fetch firstGroupleader:" + leaderstore.getLeaderId());
				return;
			}
			//添加分佣记录
			orderprofitdetail.setType(1); //(0顶级团长分佣 1二级团长分佣 2平台分佣) 原为type，修改为1

			orderprofitdetail.setLeaderId1(topLeaderstore.getLeaderId());
			orderprofitdetail.setFirstUser(firstGroupleader.getName());
			orderprofitdetail.setFirstAmount(firstLeaderComms);

			orderprofitdetail.setLeaderId2(leaderstore.getLeaderId());
			orderprofitdetail.setSecondUser(groupleader.getName());
			orderprofitdetail.setSecondAmount(secondLeaderComms);

			orderprofitdetail.setPlatAmount(platComms);
			orderprofitdetail.setMerchantId(userorder.getMerchantId());
			orderprofitdetail.setMerAmount(merchantComms);
			orderprofitdetail.setServiceCharge(serviceCharge);

			orderprofitdetail.setGmtModify(new Date());
			orderprofitdetailService.saveOrUpdate(orderprofitdetail);
			LogUtil.Info("leaderstore.getLevel()==2 save");
		}else{
			LogUtil.Info("fail leaderstore's level: " +leaderstore.getLevel() +"("+ leaderstore.getId() + ")" );
		}
	}
	
	/**
	 * 订单批量退款
	 * @param modelMap
	 * @param request
	 * @return
	 * @throws BusinessException
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping("bathRefundUserorder")
	public String bathRefundUserorder(ModelMap modelMap,HttpServletRequest request) throws BusinessException, IOException{
		String orderNo=getString("orderNo", request);
		User user=(User) HttpSessionManage.getAttribute(request, SessionKey.USER);
		Map<String, Object> prams=new HashMap<String, Object>();
		prams.put(Common.DELSTATUS, DelStatus.NODEL);
		Map<String, Object> searchParams=new HashMap<String, Object>();
		searchParams.put("orderNos", orderNo);
		Yibaopayment yibaopayment=yibaopaymentService.getByParam(prams, searchParams, null);
		if (yibaopayment==null) {
			return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "订单流水信息不存在");
		}
		prams=new HashMap<String, Object>();
		prams.put(Common.DELSTATUS, DelStatus.NODEL);
		prams.put("orderNo", orderNo);
		Userorder userorder=userorderService.getByParam(prams);
		if (userorder==null) {
			return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "订单不存在");
		}
		if (userorder.getStatus()>=2) {
			return JsonUtil.toJson(CommonInfoUtil.NOPERMISSIONS, "订单已发货无法退款");
		}	
		prams=new HashMap<String, Object>();
		prams.put(Common.DELSTATUS, DelStatus.NODEL);
		prams.put("orderNo", orderNo);	
		Yibaodivide yibaodivide=yibaodivideService.getByParam(prams);
		if (yibaodivide==null) {
			Divideresult divideresult=YibaopayUtil.yibaoDivide(yibaopayment, userorder);
			if (divideresult!=null&&divideresult.getCode().equals("OPR00000")) {
				yibaodivide=new Yibaodivide(divideresult.getStatus(), divideresult.getOrderId(), orderNo, divideresult.getUniqueOrderNo(), 
						divideresult.getDivideRequestId(), divideresult.getDivideDetail());
						yibaodivideService.saveOrUpdate(yibaodivide);
			}else {					
				return JsonUtil.toJson(CommonInfoUtil.DATAERROR,divideresult.getMessage(),divideresult);
			}
		}else {
			JSONObject jsonObject=YibaopayUtil.getYibaoDivide(yibaodivide.getOrderId(), yibaodivide.getUniqueOrderNo(), yibaodivide.getDivideRequestId());
			if (jsonObject!=null&&!jsonObject.getString("code").equals("OPR00000")) {
				return JsonUtil.toJson(CommonInfoUtil.DATAERROR,jsonObject.getString("message"),jsonObject);
			}
		}
		prams=new HashMap<String, Object>();
		prams.put(Common.DELSTATUS, DelStatus.NODEL);
		prams.put("orderNo", orderNo);
		Yibaorefund yibaorefund=yibaorefundService.getByParam(prams);
		if (yibaorefund==null) {
			Refundresult refundresult=YibaopayUtil.yibaoRefund(yibaodivide, userorder,yibaopayment);				
			if (refundresult!=null&&refundresult.getCode().equals("OPR00000")) {
				String refundOrderNo="3"+new Date().getTime()+user.getId().toString();
				refundorderService.saveOrUpdate(new Refundorder(user,0,refundOrderNo, userorder));
				yibaorefund=new Yibaorefund(refundresult,yibaopayment,userorder.getOrderNo());
				yibaorefundService.saveOrUpdate(yibaorefund);
			}else {
				return JsonUtil.toJson(CommonInfoUtil.DATAERROR, refundresult.getMessage(),refundresult);
			}
		}else {
			JSONObject data=YibaopayUtil.yibaoGetRefund(yibaorefund.getOrderId(), yibaorefund.getUniqueRefundNo(), yibaorefund.getRefundOrderNo());
			if (data!=null&&!data.getString("code").equals("OPR00000")) {
				return JsonUtil.toJson(CommonInfoUtil.DATAERROR, data.getString("message"),data);
			}					
		}
		userorder.setStatus(-1);
		userorder.setRefund(1);
		userorder.setGmtClose(new Date());
		userorderService.saveOrUpdate(userorder);			
		modelMap.put("orderNo", userorder.getOrderNo());
		return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成",modelMap);			
	}
	
	/**
	 * 修复售后退款订单
	 * @param modelMap
	 * @param request
	 * @return
	 * @throws BusinessException
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("repairRefundUserorder")
	public String repairRefundUserorder(ModelMap modelMap,HttpServletRequest request) throws BusinessException, IOException{
		Map<String, Object> prams=new HashMap<String, Object>();
		prams.put(Common.DELSTATUS, DelStatus.NODEL);
		prams.put(Common.STATUS, 5);
		List<Userorder> userorderList=userorderService.getByParams(prams);
		if (userorderList!=null&&userorderList.size()>0) {
			for (Userorder userorder : userorderList) {
				prams=new HashMap<String, Object>();
				prams.put(Common.DELSTATUS, DelStatus.NODEL);
				prams.put("orderNo", userorder.getOrderNo());
				Refundorder refundorder=refundorderService.getByParam(prams);
				if (refundorder!=null) {
					refundorder.setOrderType(1);
					refundorderService.saveOrUpdate(refundorder);
				}
			}
		}
		return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
	}

    /**
     * 佣金计算
     * @param modelMap
     * @param httpServletRequest
     * @return
     * @throws BusinessException 
     */
    @ResponseBody
    @RequestMapping("commissionCalculation")
    public String commissionCalculation(ModelMap modelMap,HttpServletRequest request) throws BusinessException{
    	Double orderAmount=getDouble("orderAmount", request);
    	//1.确定二级团长的佣金
		Double secondLeaderComms=ObjectUtil.sciCal(orderAmount*(setleaderlevelService.getLeaderRate(2)*0.01), 2);
		//2.确定一级团长佣金
		Double firstLeaderComms=ObjectUtil.sciCal(orderAmount*(setleaderlevelService.getLeaderRate(1)*0.01), 2);
		//3.计算一二级团长佣金的总和
		Double allLeaderComms=ObjectUtil.sciCal(secondLeaderComms+firstLeaderComms, 2);
		//商家佣金
		Double merchantComms=ObjectUtil.sciCal(orderAmount*(1-(15.0*0.01)), 2);
		//手续费
		Double serviceCharge=ObjectUtil.sciCal(orderAmount*0.003, 2);		
		//4.计算平台佣金
		Double platComms=ObjectUtil.sciCal(orderAmount-merchantComms-allLeaderComms-serviceCharge, 2);
		Double otherplatComms=ObjectUtil.sciCal(orderAmount-merchantComms-serviceCharge, 2);//平台佣金
		modelMap.put("订单金额", orderAmount);
		modelMap.put("顶级佳选官分佣", firstLeaderComms);
		modelMap.put("二级佳选官分佣", secondLeaderComms);
		modelMap.put("佳选官分佣总和", allLeaderComms);
		modelMap.put("平台佣金", platComms);
		modelMap.put("商家佣金", merchantComms);
		modelMap.put("手续费",serviceCharge);
		modelMap.put("不计算佳选官平台佣金", otherplatComms);
    	return JsonUtil.toJson(modelMap);
    }
}
